package jobserver

import (
	"gitee.com/scottq/go-framework/src/v1/log"
	"sync"
)

type IJob interface {
	Run() error
}

type Task = func()

//job，负责单个任务的执行
type Job struct {
	name  string
	coNum int64
	sync.WaitGroup
	jobEntity Task

	log.InvokeLog
}

func NewJob(name string, f func()) *Job {
	return &Job{
		name:      name,
		coNum:     1,
		jobEntity: f,
	}
}

func (j *Job) SetCoNum(num int64) {
	j.coNum = num
}

func (j *Job) Name() string {
	return j.name
}

func (j *Job) Run() error {
	for i := int64(0); i < j.coNum; i++ {
		j.Add(1)
		go j.run()
	}
	j.Wait()

	j.Info("job[%s] run end", j.Name())
	return nil
}

func (j *Job) run() {
	j.jobEntity()
	j.Done()
}

func (j *Job) Stop() error {
	return nil
}
